package user

import (
	"common/mildware"
	"common/models"
	"common/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

// UpdateUserImg 更新头像
// @Summary 更新头像
// @Description 更新头像
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Param object body docModel.DocUpdateImgToUserReq false "参数"
// @Param object body docModel.DocResp false "参数"
// @Security ApiKeyAuth
// @Success 200 {object} docModel.DocResp
// @Router /user/update/img [post]
func (h UHandler) UpdateUserImg(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.UpdateImgToUserReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("User:UpdateUserImg with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("User:UpdateUserImg with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//得到token - ID
	ID, _, _, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("User:UpdateUserImg mildware.GetCyrrentUserID err ")
		resp.SendServerBusy(c)
		return
	}
	userInfo, err := h.M.QueryUserInfoByID(ID)
	if err != nil {
		zap.L().Error("User:UpdateUserImg h.M.QueryUserInfoByID err ")
		resp.SendServerBusy(c)
		return
	}
	userInfo.ImageId = req.ID
	userInfo.ImageSrc = req.ImgUrl
	err = h.M.SaveUserInfo(userInfo)
	if err != nil {
		zap.L().Error("User:UpdateUserImg h.M.SaveUserInfo err ")
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
